package com.xq.exception;

import com.xq.response.Result01;
import com.xq.response.Result02;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * @title: GlobalException
 * @Author Tan
 * @Date: 2020/7/20 15:42
 * @Version 1.0
 * 全局异常类
 */
@ControllerAdvice
@Slf4j
public class GlobalException {
    /**
     *  非业务异常处理
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public Result02 exceptionAll(Exception e) {
        //日志打印
        log.error(e.getMessage());
        if (e instanceof NullPointerException) {
            return Result02.fail().message("空指针异常" + e.toString());
        }
        if (e instanceof NumberFormatException) {
            return Result02.fail().message("数字类型转换异常");
        }
        if (e instanceof ArrayIndexOutOfBoundsException) {
            return Result02.fail().message("数组越界");
        }
        if (e instanceof ArithmeticException) {
            return Result02.fail().message("算术异常");
        }
        return Result02.fail().message("其它异常:" + e.toString() + "-->请联系管理员！");
    }

    /**
     * 业务逻辑异常处理
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(BusinessException.class)
    public Result02 businessException(BusinessException e) {
        //日志打印
        log.error(e.getMsg());
        Map<String,Object> map=new HashMap<>();
        map.put("code",e.getCode());
        return Result02.fail().message(e.getMsg()).data(map);
    }
}